package com.lecture.java8.stack;

import lombok.Data;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

@Data
class DeviceTree {
    private String name;
    private int count;
    private DeviceTree parent;
    private List<DeviceTree> children;

    public DeviceTree(String name, DeviceTree parent) {
        this.name = name;
        this.count = 1; // 当前节点初始化为1
        this.parent = parent;
        this.children = new ArrayList<>();
    }

    public void addChild(DeviceTree child) {
        children.add(child);
    }

    public int getCount() {
        return count;
    }

    public void updateCount() {
        // 使用迭代方式更新 count 值
        Deque<DeviceTree> stack = new ArrayDeque<>();
        stack.push(this); // 将当前节点入栈

        while (!stack.isEmpty()) {
            DeviceTree current = stack.pop(); // 弹出栈顶节点

            if (current.parent != null) {
                current.parent.count += current.count - 1; // 减去当前节点本身的1再加上子节点的count
            }

            for (DeviceTree child : current.children) {
                stack.push(child); // 将子节点入栈
            }
        }
    }

    public String getName() {
        return name;
    }
}

